<?php
namespace App\Http\Controllers\Dashboard;
use App\Http\Controllers\Controller;
use App\Libraries\HTTPHandler;
use App\Models\CollectFile;
use App\Models\File;
use App\Models\UserFile;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }
    //获取用户列表
    public function getUsers(Request $request){
        $users = User::where(function($query) use($request){
                if ($request->input('name') != '') {
                    $query->where('nickname', 'like', '%'.$request->input('name').'%');
                }
            })
            ->where(function($query) use($request){
                if ($request->input('phone') != '') {
                    $query->where('phone', 'like', '%'.$request->input('phone').'%');
                }
            })
            ->where(function($query) use($request){
                if ($request->input('status_type') == '1') {
                    $query->where('status', '=', User::STATUS_DISABLED)->where('synced_with_qyh', User::SYNCED);
                }elseif ($request->input('status_type') == '2') {
                    $query->where('synced_with_qyh', User::NOT_SYNCED);
                }
            })
            ->orderby('id','asc')
            ->paginate(20);
        $page = isset($page)?$request['page']:1;
        $users = $users->appends(array(
            'name'=>$request->input('name'),
            'phone'=>$request->input('phone'),
            'status_type'=>$request->input('status_type'),
            'page'=>$page
        ));
        return view('admin.list_user',['users' => $users]);
    }
    //获取用户信息
    public function getOneUser($id){
        $user = User::find($id);
        return view('admin.modify_user',['user'=>$user]);
    }
    //修改用户信息
    public function modify(Request $request, $id){
        try {
            $this->validate($request, [
                'name'=>'bail|required',
                'total_storage'=>'bail|required',
//                'role'=>'bail|required|integer',
                'status'=>'bail|required|integer|in:0,1'
            ]);
        } catch (ValidationException $exception) {
            return ['code'=>1, 'msg'=>'invalid form data'];
        }
        $user = User::find($id);
        $user->name = $request->input('name');
        $user->phone = $request->input('phone');
//        $food->used_storage = $request->input('used_storage');
        $user->total_storage = $request->input('total_storage') * 1024;
        $user->role = $request->input('role');
        $user->status = $request->input('status');
        $result = $user->save();
        if($result===false){
            return ['code'=>2, "msg"=>'modify failed'];
        } else{
            return ['code'=>0, "msg"=>'success'];
        }
    }
    //启用用户
    public function enable_user($id){
        User::where('id', $id)->update(['status'=>User::STATUS_ENABLED]);
        return ['code'=>0, "msg"=>'success'];
    }
    //禁用用户
    public function disable_user($id){
        User::where('id', $id)->update(['status'=>User::STATUS_DISABLED]);
        return ['code'=>0, "msg"=>'success'];
    }
    //删除用户
    public function delete($id) {
        $user_file_id_list = UserFile::where('user_id', $id)->where('type', UserFile::TYPE_FILE)->pluck('id');
        if(!empty($user_file_id_list)){
            $user_pub_used_storage = 0;
            foreach($user_file_id_list as $user_file_id){
                CollectFile::where('user_file_id', $user_file_id)->delete();//删除掉收藏我的记录
                $user_file = UserFile::find($user_file_id);
                if($user_file->is_public == UserFile::IS_PUBLIC){
                    $user_pub_used_storage += File::where('id', $user_file->file_id)->value('storage_size');
                }
            }
            $pub_used_storage = \Illuminate\Support\Facades\DB::table('settings')->where("name", "PUB_USED_STORAGE")->value('value');
            \Illuminate\Support\Facades\DB::table('settings')->where("name", "PUB_USED_STORAGE")->update(['value'=> $pub_used_storage-$user_pub_used_storage]);
        }
        UserFile::where('user_id', $id)->delete();//@我的记录和我的文件夹、文件
        UserFile::where('from_user_id', $id)->where('type', UserFile::TYPE_SHARE_LINK)->delete();//我@的
        CollectFile::where('user_id', $id)->delete();//删除我收藏的
        User::where('id',$id)->delete();
        return ['code'=>0, "msg"=>'success'];
    }

    //获取最低级部门id列表,即没有子部门的部门
    public function getDepartments() {
//        ini_set('display_errors', 1);
//        error_reporting(E_ALL);
        $qyh_access_token = HTTPHandler::getAccessTokenQYH();
        $get_departments_api = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token={$qyh_access_token}&id=1";
        $response = HTTPHandler::http_get_data($get_departments_api);
        if($response===false) {
            return response('Cannot connected to Weixin Server.', 500);
        }
        $response = json_decode($response, true);
        $department_id_list = [];
        $parent_department_id_list = [];
        foreach ($response['department'] as $department) {
            $department_id_list[] = $department['id'];
            $parent_department_id_list[] = $department['parentid'];
        }
        DB::table('users')->update(['synced_with_qyh'=>0]);
        return ['code'=>0,'data'=>array_diff($department_id_list, $parent_department_id_list)];
    }
    //从企业微信同步通讯录
    public function syncUsers($department_id) {
        $qyh_access_token = HTTPHandler::getAccessTokenQYH();
        $get_users_api = "https://qyapi.weixin.qq.com/cgi-bin/user/list?access_token={$qyh_access_token}&department_id={$department_id}&fetch_child=0";
        $response = HTTPHandler::http_get_data($get_users_api);
        if($response===false) {
            return response('Cannot connected to Weixin Server.', 500);
        }
        $response = json_decode($response, true);
        $users = $response['userlist'];
        $i=1;
        $users_count = count($users);

        foreach ($users as $wx_user) {
            if($wx_user['status']!==1 && $wx_user['status']!==4) continue;
            $now = Date('Y-m-d H:i:s');
            $role = ($wx_user['position'] == '学生') ? 0 : 1;
            $user = DB::table('users')->select('id','nickname','avatar','phone')->where('qyh_userid', $wx_user['userid'])->first();
            if(empty($user)) {
                $user_id = DB::table('users')->insertGetId([
                    'name'=>$wx_user['userid'],
                    'qyh_userid'=>$wx_user['userid'],
                    'nickname'=>$wx_user['name'],
                    'avatar'=>urlencode($wx_user['avatar']),
                    'phone'=>$wx_user['mobile'],
                    'synced_with_qyh'=>1,
                    'role'=>$role,
                    'created_at'=>$now,
                    'updated_at'=>$now
                ]);
                if($user_id>0) {
                    DB::table('user_files')->insertGetId([
                        'user_id'=>$user_id,
                        'name'=>'Root',
                        'status'=>UserFile::STATUS_NORMAL,
                        'type'=>UserFile::TYPE_FOLDER,
                        'created_at'=>$now,
                        'updated_at'=>$now
                    ]);
                }

            } else {
                $users_update[] = [];
                DB::table('users')->where('id', $user->id)->update([
                    'nickname'=>$wx_user['name'],
                    'avatar'=>urlencode($wx_user['avatar']),
                    'phone'=>$wx_user['mobile'],
                    'synced_with_qyh'=>1,
                    'role'=>$role,
                    'updated_at'=>$now
                ]);
            }
        }
        return ['code'=>0,'msg'=>"Success"];
    }
}